package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Override
    @Transactional //事务注解
    public void saveWithFlavor(DishDTO dishDTO) {
//        插入菜品1数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.insert(dish);
//        因为在mapper中添加的参数才能获取id
        Long dishId = dish.getId();
//        向口味表插入n条数据
        List<DishFlavor> flavor = dishDTO.getFlavors();
        if(flavor!=null&&flavor.size()>0){
            flavor.forEach(dishFloavor->{
                dishFloavor.setDishId(dishId);
            });
//            批量插入
            dishFlavorMapper.insertBatch(flavor);
        }
    }

    @Override
    public DishVO getByDishId(Long id) {
        DishVO dishVO = new DishVO();
//        查菜品
        Dish dish = dishMapper.getById(id);
//        查口味
        List<DishFlavor> dishFlavor = dishFlavorMapper.getByDishId(id);
//        合并
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavor);


        return dishVO;
    }



    @Override
    public void deleteBatch(List<Long> ids) {
//        判断当前菜品是否能够删除--启售
        for(Long id:ids){
            Dish dish = dishMapper.getById(id);
            if(dish.getStatus() == StatusConstant.ENABLE){
//                不可删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
//        被套餐关联吗
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if(setmealIds!=null&&setmealIds.size()>0){
//               不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
//        删除菜品
        for (Long id : ids) {
            dishMapper.deleteById(id);
            //        还要删除关联的口味
            dishFlavorMapper.deleteByDishId(id);
        }
//        sql:delete from dish where id in (?,?,?)  sql语句中批量删除可以优化


    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
//        先把参数给pageHelper
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
//        select查询返回数据
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
//        封装pageresult
        PageResult pageResult = new PageResult(page.getTotal(),page.getResult());
        return pageResult;
    }
    @Override
    public void updateDishWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
//        修改菜品表
        dishMapper.updateDishWithFlavor(dish);
//        修改口味 先删后加
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        List<DishFlavor> flavor = dishDTO.getFlavors();
        if(flavor!=null&&flavor.size()>0){
            flavor.forEach(dishFloavor->{
                dishFloavor.setDishId(dishDTO.getId());
            });
//            批量插入
            dishFlavorMapper.insertBatch(flavor);
        }

    }
    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder().id(id).status(status).build();
        dishMapper.updateDishWithFlavor(dish);
//        如果要停售菜品，那包含菜品的套餐也要停售
        if(status==StatusConstant.DISABLE){
//            只有一个菜品为什么要放在list中？
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            // select setmeal_id from setmeal_dish where dish_id in (?,?,?)
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }
}
